/* 

auth：王宇嘉
date：2022-8-15
desc：app下使用sqlite持久保存数据。注意，只能在APP上使用。

 */

class HandleSQLiteBase {

	constructor(func, DBname = 'main', table_name = 'table1') {
		this.DBname = DBname // 库的名字
		this.table_name = table_name // 要查询的表名
		this.func = func(this.DBname, this.table_name) // 操作数据库的函数
		this.list = [] // 用于接收查询结果
		this.loading = false // 是否是加载中。
		this.state = true // 请求结果状态。成功true，失败false
		this.create_table_statements = `"id" Integer primary key,"createTime" DATETIME  not null,"type" TINYINT NOT NULL DEFAULT 1,"remark  TEXT NULL","quantity" int(10) NULL` // 创建表定义字段部分的语句。
		this.isTable()
	}

	// 打开数据库
	open() {
		this.loading = true
		plus.sqlite.openDatabase({
			name: this.DBname, //这里是数据库的名称
			path: `${plus.io.convertLocalFileSystemURL("/storage/emulated/0/")}/db.sqlite3`,  //_doc是相对路径的应用私有文档目录
			success: function(e) {
				console.log('数据库打开成功')
			},
			fail: function(e) {
				console.log('数据库打开失败:', e)
			}
		});
	}

	// 关闭数据库
	close() {
		plus.sqlite.closeDatabase({
			name: this.DBname,
			success: function(e) {
				console.log('数据库关闭成功')
			},
			fail: function(e) {
				console.log('数据库关闭失败')
			}
		})
		this.loading = false
	}

	// 判断数据库是否打开
	isOpen() {
		var bool = plus.sqlite.isOpenDatabase({
			name: 'test',
			path: '_doc/aaa.db'
		});
		console.log('数据库是否打开：' + bool)
	}
	
	//判断表是否存在
	isTable() {
		this.open()
	 	plus.sqlite.selectSql({ 
	 			name: this.DBname,
	 			sql: `select count(*) as count  from sqlite_master where type='table' and name='${this.table_name}'`,
	 			success: (data) => {
	 				if (data[0].count <= 0) {
	 					this.createTable()
	 				}
	 			},
	 			fail: (e)=> {
	 				console.log('查询失败')
	 				console.log(e)
	 			}
	 		})
		this.close()
       }
	// 创建表格
 	 createTable() {
		 this.open()
		plus.sqlite.executeSql({
		        name: this.DBname,
		        sql: `create table if not exists ${this.table_name} (${this.create_table_statements})`,
		        success: (e) => {
		            console.log(`${this.table_name} create success!`);
		            this.state = true
		        },
		        fail: (e) => { 
		            console.log(this.table_name)
		            console.log(`${this.table_name} create failed: ` + JSON.stringify(e));
		            this.state = false 
		        }
		    });
	 this.close()
	}

	// 删除表格
	 deleteTable() { 
		this.open()
		plus.sqlite.executeSql({
			name: this.DBname,
			sql: `drop table ${this.table_name}`,
			success: (e)=> {
				console.log(`drop ${this.table_name} success`)
				this.state = true
			},
			fail: (e)=> {
				console.log(`drop ${this.table_name} fail`)
				this.state = false
			}
		})
		this.close()
	}

	// 获取列表
	async getList(params) {
	    this.open();  // 打开资源或进行准备
	    try {
	        // 使用 await 等待异步操作完成
	        const res = await this.func.getList(params); 
	        // 异步操作成功，更新状态
	        this.list = res;
	        this.state = true;
			
			
	    } catch (err) {
	        // 如果异步操作失败，更新状态 
	        this.state = false;
	    }
	    this.close(); 
		 // 执行关闭操作
	}

	
	// 通用执行语句
	execute(method,params) {
		this.open()
		this.func[method](params).then(res=>{
			if (method!='insert' && method!='delete' ){
				this.getList()
			}
			this.state = true
		}).catch(err=>{
			this.state = false
		})
		this.close()
	}
}

class HandleSQLite extends HandleSQLiteBase{
	constructor(func, DBname = 'main', table_name = 'table1') {
		super(func, DBname, table_name)
		this.create_table_statements = `"id" Integer primary key AUTOINCREMENT,"createTime" DATETIME  not null,"type" TINYINT NOT NULL DEFAULT 1,"remark" TEXT NULL,"quantity" int(10) NULL` // 创建表定义字段部分的语句。
	}
	
}

export {
	HandleSQLite
}
